package my.merborn.ordersysteam105.controllers;

import my.merborn.ordersysteam105.models.dao.UserMapper;
import my.merborn.ordersysteam105.models.pojo.User;
import my.merborn.ordersysteam105.models.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
public class UserController {

    @Autowired
    UserService us;

    @Autowired
    UserMapper um;

    @RequestMapping(value = "/register.do", method = RequestMethod.POST)
    public ModelAndView register(User user) {
        ModelAndView mv = new ModelAndView();
       // System.out.println(user.getuGender());
        if (us.registUser(user)) {
            mv.setViewName("redirect:userlogin.html");
        } else {
            mv.setViewName("redirect:Register.html");
        }
        return mv;
    }

    @RequestMapping(value = "/logincheck.do", method  = RequestMethod.POST)
    public ModelAndView login(@RequestParam(required = false) String userName, @RequestParam(required = false) String pwd, HttpServletRequest request) {

        ModelAndView mv = new ModelAndView();
        if (us.loginCheck(userName, pwd)) {

            mv.setViewName("userinfo.html");
            User user = um.selectByName(userName);
            request.getSession().setAttribute("uid",user.getuId());
            mv.addObject("userName", user.getuName());
            mv.addObject("userId", user.getuId());
            mv.addObject("userPower", user.getuPower());
        } else {
            request.getSession().setAttribute("uid","");
            mv.setViewName("redirect:userlogin.html");
        }
        return mv;
    }

    @GetMapping("/userinfo.html")
    public ModelAndView userinfo(HttpServletRequest request){
        Integer uid = (Integer) request.getSession().getAttribute("uid");
        User user = us.getUserById(uid);
        //System.out.println(user);
        ModelAndView mv = new ModelAndView("userinfo.html");
        mv.addObject("userName", user.getuName());
        mv.addObject("userId", user.getuId());
        mv.addObject("userPower", user.getuPower());
        return mv;
    }
}
